﻿using System;
using System.Collections.Generic;
using Microsoft.SharePoint;
using WoltersKluwer.SPChainGang.Core.Constants;
using WoltersKluwer.SPChainGang.Core.Util;

namespace WoltersKluwer.SPChainGang.Core.ObjectScanners
{
    public class CompositeScanner : ScannerBase
    {
        List<ScannerBase> scanners = new List<ScannerBase>();

        public CompositeScanner(string name, SPSite targetSiteCollection, Guid configurationListId, JobMode mode, Guid jobId)
            : base(name, targetSiteCollection, configurationListId, mode, jobId)
        {
            scanners.Add(new SiteListsScanner(targetSiteCollection, configurationListId, mode, jobId, ReportTempFilename, Mappings));
            scanners.Add(new SitePagesScanner(targetSiteCollection, configurationListId, mode, jobId, ReportTempFilename, Mappings));
        }

        public override void Scan(SPWeb web)
        {
            foreach (var scanner in scanners)
            {
                try
                {
#if SOS
                    Logger.Log(JobId, "Cleaning up before starting a scanner module {0}", scanner);
#endif
                    GC.WaitForPendingFinalizers(); //TODO: profile the application
                    GC.Collect();
#if SOS
                    Logger.Log(JobId, "Starting a scanner module {0} for web {1}", scanner, web.Url);
#endif
                    scanner.Scan(web);
                }
                catch (OutOfMemoryException)
                {
                    throw;
                }
                catch (Exception e)
                {
                    Logger.LogError(JobId, String.Format("Scanner '{0}' crashed.", scanner), e);
                }                
            }
        }
    }
}
